import React, { memo, useEffect } from 'react'
import type { FC, ReactNode } from 'react'

import { RankingWrapper } from './style'
import AreaHeader from '@/components/area-header'
import { useAppDispatch, useAppSelector } from '@/store'
import { fetchDiscoverRankList } from '@/store/modules/discover'
import { forMatImageUrl } from '@/utlis/format'
import { fetchByIdGetSongDetailAction } from '@/store/modules/audio'
interface IProps {
  children?: ReactNode
}

const Ranking: FC<IProps> = () => {
  const dispatch = useAppDispatch()

  // 获得排行榜数据
  useEffect(() => {
    dispatch(fetchDiscoverRankList())
  }, [])

  const { rankList } = useAppSelector((state) => {
    return {
      rankList: state.discover.rankList
    }
  })

  // 点击播放音乐
  const playAudio = (id: number) => {
    dispatch(fetchByIdGetSongDetailAction(id))
  }

  return (
    <RankingWrapper>
      {/* 头部 */}
      <AreaHeader
        title="榜单"
        moreText="更多"
        moreLink="/discover/ranking"
      ></AreaHeader>

      {/* 内容 */}
      <div className="content">
        {rankList.map((item) => {
          return (
            <div className="ranking_item" key={item.id}>
              <div className="ranking_item_top">
                <img
                  src={forMatImageUrl(item.coverImgUrl, 80)}
                  className="image"
                />
                <div className="right">
                  <h3 className="title">{item.name}</h3>
                  <div className="bottom">
                    <a className="icon sprite_02 play">播放</a>
                    <a className="icon sprite_02 favor">收藏</a>
                  </div>
                </div>
              </div>
              {/* tracks */}
              <div className="ranking_item_bottom">
                <ul className="bottom_ul">
                  {item.tracks.slice(0, 10).map((m: any, mi: number) => {
                    return (
                      <li className="bottom_li" key={mi}>
                        <span className="song_rank">{mi + 1}</span>
                        <span className="song_name">{m.name}</span>
                        <span className="icon">
                          <button
                            className="sprite_02 play ib"
                            onClick={() => playAudio(m.id)}
                          ></button>
                          <button className="sprite_icon2 add ib"></button>
                          <button className="sprite_02 favor ib"></button>
                        </span>
                      </li>
                    )
                  })}
                  <li className="bottom_li">
                    <span className="song_name more">查看更多 &gt;</span>
                  </li>
                </ul>
              </div>
            </div>
          )
        })}
      </div>
    </RankingWrapper>
  )
}

export default memo(Ranking)
